#!/bin/bash

source $current_dir/script/logger.sh
source $current_dir/script/render.sh

ld_cache_file="$current_dir/script/ld.so.cache"

build_ld_cache()
{
    local so_search_path=$(echo $LIBRARY_PATH:$LD_LIBRARY_PATH:/usr/lib64|tr ':' '\n'|sort|uniq|xargs readlink -f|tr '\n' ' ')
    ldconfig -C $ld_cache_file $so_search_path 2>/dev/null
}

get_pretty_os_name() {
    # Obtain the os name
    local pretty_os_name=$(cat /etc/os-release | grep "PRETTY_NAME" | awk -F '"' '{print $2}')
    pretty_os_name=${pretty_os_name// /} # remove white space
    if [[ ${pretty_os_name} =~ "CentOSLinux" ]]; then
        local red_os=$(cat /etc/redhat-release)
        red_os=${red_os// /}
        [[ ${red_os} =~ "CentOSLinuxrelease7.6.1810" ]] && pretty_os_name="CentOSLinuxrelease7.6.1810"
    fi
    echo "${pretty_os_name}"
}

check_dep_bin()
{
    local bin_name=$1
    if ! command -v ${bin_name} &> /dev/null; then
        logWarn "$bin_name required, Please install via yum install $bin_name."
        continue_install
    fi
}

get_so_version() {
    local so_full_name="$1"
    local so_name=`basename $so_full_name`
    local version=""
    if [[ $so_name == *.so ]]; then
        # example libc-2.17.so
        version=`echo $so_name | awk -F'-|.so' '{print $2}'`
    else
        # example libssl.so.1.0.2k
        version=`echo $so_name | awk -F'.so.' '{print $2}'`
    fi
    echo $version
    # keep only number and .
    # echo $version | tr -cd '0-9.'
}

function V() # $1-a $2-op $3-$b
# Compare a and b as version strings. Rules:
# R1: a and b : dot-separated sequence of items. Items are numeric. The last item can optionally end with letters, i.e., 2.5 or 2.5a.
# R2: Zeros are automatically inserted to compare the same number of items, i.e., 1.0 < 1.0.1 means 1.0.0 < 1.0.1 => yes.
# R3: op can be '=' '==' '!=' '<' '<=' '>' '>=' (lexicographic).
# R4: Unrestricted number of digits of any item, i.e., 3.0003 > 3.0000004.
# R5: Unrestricted number of items.
#
{
    local a=$1 op=$2 b=$3 al=${1##*.} bl=${3##*.}
    while [[ $al =~ ^[[:digit:]] ]]; do al=${al:1}; done
    while [[ $bl =~ ^[[:digit:]] ]]; do bl=${bl:1}; done
    local ai=${a%$al} bi=${b%$bl}

    local ap=${ai//[[:digit:]]} bp=${bi//[[:digit:]]}
    ap=${ap//./.0} bp=${bp//./.0}

    local w=1 fmt=$a.$b x IFS=.
    for x in $fmt; do [ ${#x} -gt $w ] && w=${#x}; done
    fmt=${*//[^.]}; fmt=${fmt//./%${w}s}
    printf -v a $fmt $ai$bp; printf -v a "%s-%${w}s" $a $al
    printf -v b $fmt $bi$ap; printf -v b "%s-%${w}s" $b $bl

    case $op in
        '<='|'>=' ) [ "$a" ${op:0:1} "$b" ] || [ "$a" = "$b" ] ;;
        * )         [ "$a" $op "$b" ] ;;
    esac
}

check_dep_so()
{
    local line="$1"
    local cmp=$(echo $line | grep -oE '[>=<]+')
    local so_name=$(echo $line | awk -F '[>=<]+' '{print $1}')
    local so_version=$(echo $line | awk -F '[>=<]+' '{print $2}')
    # process soft link
    local so_found=`ldconfig -C $ld_cache_file -p | grep -F $so_name | awk '{print $NF}' | xargs readlink -f 2>/dev/null`
    for so in ${so_found[@]}; do
        local version=`get_so_version $so`
        V $version $cmp $so_version
        if [[ $? -eq 0 ]]; then
            # echo $so_name $version $cmp $so_version
            return
        fi
    done
    logWarn "$line required, Please update the library to the required version."
    continue_install
}

check_dep()
{
    local file_name="$1"
    if [ ! -e "$file_name" ]; then
        return
    fi
    build_ld_cache
    while IFS= read -r -u 3 line || [ -n "$line" ] ; do
        # trim \r at end of line
        line=$(echo "$line" | sed -e 's/\r//g')
        case "$line" in
        "")
            ;;
        *.so*)
            check_dep_so "$line"
            ;;
        *)
            check_dep_bin "$line"
            ;;
        esac
    done 3< $file_name
}

# check_dep script/requirement.conf